package cn.iocoder.yudao.module.picturebook.service.audio;

import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.plan.PlanDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.book.BookMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.bookgather.BookGatherMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.favorites.FavoritesMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.plan.PlanMapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.util.*;

import cn.iocoder.yudao.module.picturebook.controller.admin.audio.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.audio.AudioDO;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.audio.AudioMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 绘本全音频 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AudioServiceImpl implements AudioService {

    @Resource
    private AudioMapper audioMapper;
    @Resource
    private BookMapper bookMapper;
    @Resource
    private BookGatherMapper bookGatherMapper;
    @Resource
    private FavoritesMapper favoritesMapper;
    @Resource
    private PlanMapper planMapper;

    /**
     * 创建绘本音频记录
     *
     * @param createReqVO 音频创建请求VO，包含音频相关信息
     * @return 音频ID，创建成功后返回的主键ID
     * @throws RuntimeException 当音频创建失败或audioId为空时抛出异常
     */
    @Override
    public Integer createAudio(AudioSaveReqVO createReqVO) {
        // 插入音频记录到数据库
        AudioDO audio = BeanUtils.toBean(createReqVO, AudioDO.class);
        audioMapper.insert(audio);

        // 添加空值检查
        if (audio.getAudioId() == null) {
            throw new RuntimeException("Failed to create audio, audioId is null");
        }

        // 返回新创建的音频ID
        return audio.getAudioId();
    }


    @Override
    public void updateAudio(AudioSaveReqVO updateReqVO) {
        // 校验存在
        validateAudioExists(updateReqVO.getAudioId());
        // 更新
        AudioDO updateObj = BeanUtils.toBean(updateReqVO, AudioDO.class);
        audioMapper.updateById(updateObj);
    }

    @Override
    public void deleteAudio(Integer id) {
        // 校验存在
        validateAudioExists(id);
        // 删除
        audioMapper.deleteById(id);
    }

    @Override
    public void deleteAudioListByIds(List<Integer> ids) {
        // 删除
        audioMapper.deleteByIds(ids);
    }


    private void validateAudioExists(Integer id) {
        if (audioMapper.selectById(id) == null) {
            throw exception(AUDIO_NOT_EXISTS);
        }
    }

    @Override
    public AudioDO getAudio(Integer id) {
        return audioMapper.selectById(id);
    }

    @Override
    public AudioVO getAudioPage(AudioPageReqVO pageReqVO) {
        AudioVO audioVO = new AudioVO();
        //根据集合id查询绘本
        List<BookDO> byGatherId = bookMapper.getByGatherId(pageReqVO.getBookGaterId());
        //获取绘本集的名字
        String gatherName = null;
        if (bookGatherMapper.selectById(pageReqVO.getBookGaterId()) != null) {
            gatherName = bookGatherMapper.selectById(pageReqVO.getBookGaterId()).getGaterName();
        }
        List<AudioRespVO> audioRespVOList = new ArrayList<>();
        if (gatherName != null) {
            audioVO.setGatherName(gatherName);
        } else {
            audioVO.setGatherName("");
        }
        audioVO.setBookCount(byGatherId != null ? byGatherId.size() : 0);
        if (byGatherId != null) {
            for (BookDO bookDO : byGatherId) {
                if (bookDO != null) {
                    AudioRespVO audioRespVO = new AudioRespVO();
                    audioRespVO.setBookName(bookDO.getTitle());
                    audioRespVO.setBookId(bookDO.getId());
                    audioRespVO.setBookCover(bookDO.getCoverUrl());
                    //查询当前绘本的音频
                    AudioDO audioDO = audioMapper.selectByBookId(bookDO.getId());
                    if (audioDO != null) {
                        audioRespVO.setAudioId(audioDO.getAudioId());
                        audioRespVO.setAudioIdUrl(audioDO.getAudioIdUrl());
                    }
                    audioRespVOList.add(audioRespVO);
                }
            }
        }
        audioVO.setAudioList(audioRespVOList);
        return audioVO;
    }


    @Override
    public AudioVO getFavoritesAudio(Long userId) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 查询当前用户收藏的绘本
        List<Long> bookIds = favoritesMapper.selectBookIdsByUserId(userId);
        AudioVO audioVO = new AudioVO();
        audioVO.setGatherName("收藏的绘本");
        audioVO.setBookCount(bookIds != null ? bookIds.size() : 0);
        List<AudioRespVO> audioRespVOList = new ArrayList<>();

        // 获取绘本的音频
        if (bookIds != null) {
            for (Long bookId : bookIds) {
                if (bookId != null) {
                    AudioDO audioDO = audioMapper.selectByBookId(bookId);
                    //获取绘本的信息
                    BookDO bookDO = bookMapper.selectById(bookId);
                    AudioRespVO audioRespVO = getAudioRespVO(bookId, bookDO, audioDO);
                    audioRespVOList.add(audioRespVO);
                }
            }
        }
        audioVO.setAudioList(audioRespVOList);
        return audioVO;
    }

    @NotNull
    private static AudioRespVO getAudioRespVO(Long bookId, BookDO bookDO, AudioDO audioDO) {
        AudioRespVO audioRespVO = new AudioRespVO();
        if (bookDO != null) {
            audioRespVO.setBookName(bookDO.getTitle());
            audioRespVO.setBookId(bookId);
            audioRespVO.setBookCover(bookDO.getCoverUrl());
        }
        if (audioDO != null) {
            audioRespVO.setAudioId(audioDO.getAudioId());
            audioRespVO.setAudioIdUrl(audioDO.getAudioIdUrl());
        }
        return audioRespVO;
    }

    @Override
    public AudioVO getPlanContentAudio(Long bigPlanId) {
        // 1. 参数校验
        if (bigPlanId == null) {
            throw new IllegalArgumentException("计划ID不能为空");
        }

        // 2. 查询计划内容并验证结果
        LocalDate now = LocalDate.now();
        PlanDO planByBigPlanIdAndTime = planMapper.getPlanByBigPlanIdAndTime(Math.toIntExact(bigPlanId), now);
        List<Integer> planBookList = getIntegers(planByBigPlanIdAndTime);

        AudioVO audioVO = new AudioVO();
        audioVO.setGatherName("计划");
        audioVO.setBookCount(planBookList.size());
        List<AudioRespVO> audioRespVOList = new ArrayList<>();

        // 5. 查询书籍和音频信息并验证
        for (Integer bookId : planBookList) {
            if (bookId != null) {
                // 验证书籍是否存在
                BookDO bookDO = bookMapper.selectById(Long.valueOf(bookId));
                if (bookDO == null) {
                    throw new RuntimeException("书籍不存在，ID: " + bookId);
                }

                // 验证音频是否存在
                AudioDO audioDO = audioMapper.selectByBookId(Long.valueOf(bookId));
                if (audioDO == null) {
                    throw new RuntimeException("书籍音频不存在，书籍ID: " + bookId);
                }

                AudioRespVO audioRespVO = new AudioRespVO();
                audioRespVO.setBookName(bookDO.getTitle());
                audioRespVO.setBookCover(bookDO.getCoverUrl());
                audioRespVO.setBookId(Long.valueOf(bookId));
                audioRespVO.setAudioIdUrl(audioDO.getAudioIdUrl());
                audioRespVOList.add(audioRespVO);
            }
        }

        audioVO.setAudioList(audioRespVOList);
        return audioVO;
    }

    @NotNull
    private static List<Integer> getIntegers(PlanDO planByBigPlanIdAndTime) {
        if (planByBigPlanIdAndTime == null) {
            throw new RuntimeException("未找到对应的大计划内容");
        }

        // 3. 验证计划书籍内容
        String planBook = planByBigPlanIdAndTime.getPlanBook();
        if (planBook == null || planBook.trim().isEmpty()) {
            throw new RuntimeException("计划内容为空");
        }

        // 4. 解析书籍列表并处理可能的格式异常
        List<Integer> planBookList = new ArrayList<>();
        try {
            String[] bookIds = planBook.split(",");
            for (String bookIdStr : bookIds) {
                if (bookIdStr != null && !bookIdStr.trim().isEmpty()) {
                    planBookList.add(Integer.parseInt(bookIdStr.trim()));
                }
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException("计划书籍格式不正确", e);
        }
        return planBookList;
    }


}